/**
 * Created by jackbean on 16/12/15.
 */function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

$(function() {
    validatePermission()
    var userId = $.cookie('userId');
    //异常订单管理、正常订单管理、特殊订单管理判断
    var path = $.getUrlParam('path');
    var pag=$.getUrlParam('pag');
    if( pag == null || pag==undefined || pag==""){
        pag=1;
    }
    //浏览器带搜索参数
    var tid = $.getUrlParam('tid');
    if( tid == null || tid==undefined || tid==""){
        tid=$("#tid").val() || "";
    }
    var type = $.getUrlParam('type');
    if( type == null || type==undefined || type==""){
        type=  $("#type").val() || "";
    }
    var receiverMobile = $.getUrlParam('receiverMobile');
    if( receiverMobile == null || receiverMobile==undefined || receiverMobile==""){
        receiverMobile=  $("#third_mobile").val() || "";
    }
    var startTime = $.getUrlParam('startTime');
    if( startTime == null || startTime==undefined || startTime==""){
        startTime=  $("#selStartTime").val() || "";
    }
    var endTime = $.getUrlParam('endTime');
    if( endTime == null || endTime==undefined || endTime==""){
        endTime=  $("#selEndTime").val() || "";
    }
    var receiverState = $.getUrlParam('receiverState');
    if( receiverState == null || receiverState==undefined || receiverState==""){
        receiverState=  $("#province").val() || "";
    }
    var receiverName = $.getUrlParam('receiverName');
    if( receiverName == null || receiverName==undefined || receiverName==""){
        receiverName=  $("#third_Consignee").val() || "";
    }
    var feedback = $.getUrlParam('feedback');
    if( feedback == null || feedback==undefined || feedback==""){
        feedback=  $("#feedback").val() || "";
    }
    var status = $.getUrlParam('status');
    if( status == null || status==undefined || status==""){
        status=  $("#status").val() || "";
    }
    var pullStatus;
    if(path == "/exception"){//异常订单管理
        pullStatus = "-103|-104|-100|-105";
        //设置显示
        $('#imporatOrder').hide();
        $("#exportOrders,#exportSku,#importOrders,#importSku,#importSpecial").show();
    }
    if(path == "/normal"){//正常订单管理
        pullStatus = "200";
        //设置隐藏
        $('#imporatOrder').show();
        $("#exportOrders,#exportSku,#importOrders,#importSku,#importSpecial,#checkList,#importList").hide();
    }
    if(path == "/special"){//特殊订单管理
        pullStatus = "-200";
        //设置隐藏
        $("#exportOrders,#exportSku,#importOrders,#importSku,#imporatOrder,#importSpecial,#checkList,#importList").hide();
    }
    //日期显示
    var start = {
        format: 'YYYY-MM-DD hh:mm:ss',
        hmsSetVal:{hh:00,mm:00,ss:00},
        isinitVal:false,
        ishmsVal:false,
        maxDate: '2099-06-30 23:59:59', //最大日期
        choosefun: function(elem,datas){
            end.minDate = datas; //开始日选好后，重置结束日的最小日期
        }
    };
    var end = {
        format: 'YYYY-MM-DD hh:mm:ss',
        hmsSetVal:{hh:23,mm:59,ss:59},
        isinitVal:false,
        maxDate: '2099-06-16 23:59:59', //最大日期
        choosefun: function(elem,datas){
            start.maxDate = datas; //将结束日的初始值设定为开始日的最大日期
        }
    };
    $('#selStartTime').jeDate(start);
    $('#selEndTime').jeDate(end);
    //另一种进度条
    var options = {
        complete: function(response)
        {//上传完成

            if(response) {
                var res = JSON.parse(response.responseText);
                if(res.status == 200){
                    common.lightBox.showMessage("操作已完成，请点击查看导入文件列表!");
                }else{
                    $("#exportExceptionModal").modal("hide");
                    common.lightBox.showMessage("导入文件格式无效，请重新上传。");
                }
            }
        },
        // headers: {Cookies : allCookies},
        error: function()
        {//上传失败报错
            $("#message").html("<font color='red'> 导入文件格式无效，请重新上传。</font>");
            $("#guanbi").css("display","block");
        }
    };
    $("#myForm1").attr("action", excelurl + "importExcel/importExceptionAddress?userId="+userId);
    $("#myForm2").attr("action", excelurl + "importExcel/importExceptionSku?userId="+userId);
    $("#myForm3").attr("action", excelurl + "importExcel/importSpecialOrder?userId="+userId);
    $('#myForm1,#myForm2,#myForm3').attr("method", "post");
    $("#myForm1,#myForm2,#myForm3").ajaxForm(options);

    //选择文件以后,需要触发提交,然后弹出进度条的框
    $("input[type=file]").on("change", function () {
        $(this).parent().submit();

    });

    window.vm = new Vue({
        el:"body",//指的是,Vue需要监听的范围,这个地方写body是为了监听整个页面,也可以控制某一块区域
        data:{
            "curNum":1,
            "curIndex":pag,
            "pageList":11,
            "totalPage":0,
            "totalNum":0,
            "total":"",
            // "provinces":provinces,
            "tid":tid,
            "pullStatus": "",
            "type":type,
            "startTime":startTime,
            "endTime":endTime,
            "receiverState":receiverState,
            "receiverName":receiverName,
            "receiverMobile":receiverMobile,
            "status":status,
            "feedback":feedback,
            "page": "1",//当前第几页
            "limit": "20",//每页多少条
            "YouzanOrderList":[],//列表数据list
            "curStatus":1,
            "path":path
        },
        ready:function () {
            this.getOrderList(pag);//初始化,第一次进来查询商品列表
            this.excOrderFileUpload();
            this.excOrderFileSku();
            this.excOrderFileSpecial();
        },
        filters: {//过滤器
            typeFilter: function (value) {
                switch(value){
                    case "FIXED":
                        return "一口价";
                    case "GROUP":
                        return "拼团订单";
                }
            },
            feedbackFilter: function (value) {
                switch(value){
                    case 101:
                        return "维权中";
                    case 110:
                        return "维权结束";
                }
            },
            pullStatusFilter: function(value) {
                switch(value){
                    case -100:
                        return "无商家编码";
                    case -103:
                        return "促销信息错误";
                    case -104:
                        return "促销商品错误";
                    case -105:
                        return "无地址信息";
                }
            },
            statusFilter: function (value,refundState) {
                //判断选择的是订单还是退货
                var state = this.curStatus;
                //如果是1,则根据status来获取值,如果是2,根据refundState来获取值
                if(state==2){
                    value = refundState;
                }
                switch(value){
                    case "WAIT_BUYER_PAY":
                        return "待付款";
                    case "WAIT_GROUP":
                        return "等待成团";
                    case "TRADE_NO_CREATE_PAY":
                        return "没有创建支付交易";
                    case "WAIT_PAY_RETURN":
                        return "等待支付确认";
                    case "WAIT_SELLER_SEND_GOODS":
                        return "待发货";
                    case "WAIT_BUYER_CONFIRM_GOODS":
                        return "已发货";
                    case "TRADE_BUYER_SIGNED":
                        return "已完成";
                    case "TRADE_CLOSED":
                        return "已关闭";
                    case "TRADE_CLOSED_BY_USER":
                        return "已关闭";
                    case "FULL_REFUNDING":
                        return "全额退款中";
                    case "PARTIAL_REFUNDING":
                        return "部分退款中";
                }
            }
        },
        methods:{
            pageInit:function (pageNum) {
                if(pageNum==1 || 9+pageNum-5<this.totalPage || this.totalPage<=11){
                    if(this.totalPage<=11){
                        this.curNum = 1;
                    }else if(pageNum-5>0){
                        this.curNum = pageNum-5;
                    }else if(this.totalPage>11){
                        this.curNum = 1;
                    }
                }else if(pageNum>1){
                    if(pageNum-5>0){
                        this.curNum = this.totalPage-10;
                    }
                }
                this.curIndex = parseInt(pageNum);
            },
            setPage:function (totalNum,pageNum) {
                //根据一页10条,计算一共有多少页
                this.totalPage = Math.ceil(totalNum/20);
                if(this.totalPage<12){
                    //如果不满11页,那么保存当前的总页数,比如可能只有5页,那么totalPage=5
                    this.pageList = this.totalPage;
                }else{
                    this.pageList = 11;//默认最多显示11页
                }
                this.pageInit(pageNum);
            },
            checkType:function (type) {
                switch (type){
                    case "WAIT_BUYER_PAY":
                    case "WAIT_GROUP":
                    case "TRADE_NO_CREATE_PAY":
                    case "WAIT_PAY_RETURN":
                    case "WAIT_SELLER_SEND_GOODS":
                    case "WAIT_BUYER_CONFIRM_GOODS":
                    case "TRADE_BUYER_SIGNED":
                    case "TRADE_CLOSED":
                    case "TRADE_CLOSED_BY_USER":
                    case "TRADE_CLOSED|TRADE_CLOSED_BY_USER":
                        return 1;
                    case "FULL_REFUNDING":
                    case "PARTIAL_REFUNDING":
                        return 2;
                    case "FULL_REFUNDING|PARTIAL_REFUNDING":
                        return 2;
                }
            },
            //查询商品列表
            getOrderList: function (pageNum) {
                var _this = this;
                var tidReg = /^E/g;
                if(this.tid && !tidReg.test(this.tid)){
                    common.lightBox.showMessage("请输入正确的三方订单编号！");
                    return;
                }
                var reg = /^[0-9]{11}$/g;
                //判断手机号
                if(this.receiverMobile && !reg.test(this.receiverMobile)){
                    common.lightBox.showMessage("手机号输入错误,请重新填写!");
                    return;
                }else {}
                _this.YouzanOrderList = [];
                var type = this.checkType(this.status);
                //截止时间不能比起始时间大
                var start = new Date($("#selStartTime").val().replace("-", "/").replace("-", "/"));
                var end = new Date($("#selEndTime").val().replace("-", "/").replace("-", "/"));
                if (end < start) {
                    _this.YouzanOrderList = [];
                    common.lightBox.showMessage("下单开始时间不能大于下单结束时间。");
                    return false;
                }
                common.lightBox.showLoading();
                //接口请求
                $.postRequest(thirdorderurl+"youzanorder/searchOrderInfo",{
                    "str" : JSON.stringify({
                        "tid": this.tid,
                        "pullStatus": pullStatus,
                        "type": this.type,
                        "startTime": $("#selStartTime").val(),
                        "endTime": $("#selEndTime").val(),
                        "receiverState":this.receiverState,
                        "receiverName": this.receiverName,
                        "receiverMobile":this.receiverMobile,
                        "refundState":type=="1"?"":this.status,
                        "status": type=="1"?this.status:"",
                        "feedback": this.feedback,
                        "page": parseInt(this.curIndex),
                        "limit": "20"
                    })
                },function (res) {
                    common.lightBox.hideLoading();
                    console.log(res);
                    if (res.result.YouzanOrderList.length!= 0) {
                        console.log(res);
                        //把接口返回的值保存到userList中
                        _this.YouzanOrderList = res.result.YouzanOrderList;
                        _this.curStatus = type;
                        _this.setPage(res.result.total,parseInt(pageNum));
                        _this.totalNum = res.result.total;
                        $("#tab").empty();
                        // alert('aaa');
                    }else{
                        _this.totalNum=0;
                        _this.YouzanOrderList = [];
                        // common.lightBox.showMessage("查询失败.");
                        $("#tab").html('<td style="font-size: 20px;font-family:Helvetica Neue, Helvetica, Arial, sans-serif;"colspan="14">没有数据</td>')
                    }
                });
            },
            prevPage:function () {
                if(this.curIndex==1){
                    return;
                }
                this.turnPage(this.curIndex-1);
                //this.getOrderList(this.curIndex-1);
            },
            nextPage:function () {
                if(this.curIndex==this.totalPage){
                    return;
                }
                this.turnPage(this.curIndex+1);
                //this.getOrderList(this.curIndex+1);
            },
            turnPage:function(pageNo){
                //this.pageInit(pageNo);
                window.location.href  = window.location.pathname + "?path="+ path+"&pag="+pageNo+"&tid="+this.tid+"&type="+this.type
                    +"&receiverMobile="+this.receiverMobile+"&startTime="+$("#selStartTime").val()+"&endTime="+$("#selEndTime").val()+"&receiverState="+this.receiverState
                    +"&receiverName="+this.receiverName+"&feedback="+this.feedback+"&status="+this.status;
                $("#tid").val("");
                $("#third_mobile").val("");
                $("#selStartTime").val("");
                $("#selEndTime").val("");
                $("#third_Consignee").val("");
                //this.getOrderList(pageNo);
            },
            exportSku:function(){//判断导出异常SKU表

            },
            exportlistSku:function () {
                var _this = this;
                var pullStatus = "-103|-104|-100";
                //  $("#str").val(JSON.stringify({"pullStatusList": arry}));
                var type = this.checkType(this.status);
                var param = JSON.stringify({
                    "tid": this.tid,
                    "pullStatus": pullStatus,
                    "type": this.type,
                    "startTime": $("#selStartTime").val(),
                    "endTime": $("#selEndTime").val(),
                    "receiverState":this.receiverState,
                    "receiverName": this.receiverName,
                    "receiverMobile":this.receiverMobile,
                    "refundState":type=="1"?"":this.status,
                    "status": type=="1"?this.status:"",
                    "feedback": this.feedback,
                    "total":this.total

                });
                $.postRequest(thirdorderurl+"excelmanager/selectExportCount",{"str":param},function(res){
                    if(res.result.total){
                        _this.total = res.result.total ;
                        $("#exportlistSku").modal('show');
                    }else{
                        //说明没有数据
                        common.lightBox.showMessage("没有查询到异常SKU数据！");
                    }
                });
            },
            exportordersSku:function () {//cook判断导出异常订单表
                var pullStatus = "-103|-104|-100";
                //  $("#str").val(JSON.stringify({"pullStatusList": arry}));
                var type = this.checkType(this.status);
                var param = JSON.stringify({
                    "tid": this.tid,
                    "pullStatus": pullStatus,
                    "type": this.type,
                    "startTime": $("#selStartTime").val(),
                    "endTime": $("#selEndTime").val(),
                    "receiverState":this.receiverState,
                    "receiverName": this.receiverName,
                    "receiverMobile":this.receiverMobile,
                    "refundState":type=="1"?"":this.status,
                    "status": type=="1"?this.status:"",
                    "feedback": this.feedback
                });
                $.ajax({//cook方式传值
                    url: thirdorderurl+"excelmanager/hasExceptionSku",
                    type:"post",
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    dataType: "json",
                    data:{
                        "str" : param
                    },
                    success: function (res) {
                        if(res.result.hasExceptionSku){
                            common.lightBox.showMessage("操作已完成，请点击查看导出文件列表!");

                        }else{
                            //说明没有数据
                            common.lightBox.showMessage("没有查询到异常订单数据！");
                        }
                    }
                });
            },
            exportAddress:function() {

            },
            exportList:function () {//判断导出异常订单表
                var _this = this;
                var pullStatus = "-105";
                var type = this.checkType(this.status);
                var param = JSON.stringify({
                    "tid": this.tid,
                    "pullStatus": pullStatus,
                    "type": this.type,
                    "startTime": $("#selStartTime").val(),
                    "endTime": $("#selEndTime").val(),
                    "receiverState":this.receiverState,
                    "receiverName": this.receiverName,
                    "receiverMobile":this.receiverMobile,
                    "refundState":type=="1"?"":this.status,
                    "status": type=="1"?this.status:"",
                    "feedback": this.feedback,
                    "total":this.total
                });
                $.postRequest(thirdorderurl + "excelmanager/selectExportCount", {"str":param}, function (res) {
                    if (res.result.total) {
                        _this.total = res.result.total ;
                        $("#exportList").modal('show');

                    } else {
                        //说明没有数据
                        common.lightBox.showMessage("没有查询到异常订单数据！");
                    }
                });
            },
            exportOrders:function () {//cook判断导出异常订单表
                var pullStatus = "-105";
                var type = this.checkType(this.status);
                var param = JSON.stringify({
                    "tid": this.tid,
                    "pullStatus": pullStatus,
                    "type": this.type,
                    "startTime": $("#selStartTime").val(),
                    "endTime": $("#selEndTime").val(),
                    "receiverState":this.receiverState,
                    "receiverName": this.receiverName,
                    "receiverMobile":this.receiverMobile,
                    "refundState":type=="1"?"":this.status,
                    "status": type=="1"?this.status:"",
                    "feedback": this.feedback
                });
                $.ajax({//cook方式传值
                    url: thirdorderurl + "excelmanager/hasExceptionAddress",
                    type:"post",
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    dataType: "json",
                    data:{
                        "str" : param
                    },
                    success: function (res) {
                        if(res.result.hasExceptionAddress){
                            common.lightBox.showMessage("操作已完成，请点击查看导出文件列表!");

                        }else{
                            //说明没有数据
                            common.lightBox.showMessage("没有查询到异常订单数据！");
                        }
                    }
                });

            },
            excOrderFileUpload: function () {//导入异常订单
                var _this = this;
            },
            excOrderFileSku: function () {//导入异常SKU
                var _this = this;
            },
            excOrderFileSpecial: function () {//导入特殊订单
                var _this = this;
            },
            imporatyouzanOrder:function () {//清空文本框
                $("#tids").val("");
                $("#imporatModal").modal("show");
            },
            pullOrder:function() {//判断导入有赞订单
                var tids = $("#tids").val();
                // alert(tids);
                //判断是否为空
                if(tids==""){
                    common.lightBox.showMessage("请输入有赞订单编号!");
                }else{
                    // alert("111");
                    $.ajax({url:auxiliaryurl + "youzanOrder/pullOrder.jsonp",dataType:'jsonp', type: 'get',
                        data:{"tids":tids},
                        success:function (res) {
                            if (res.status == "200") {
                                common.lightBox.showMessage(res.message);
                            }else{
                                common.lightBox.showMessage(res.message);
                            }
                            $("#imporatModal").modal('hide');
                        }
                    });
                }
            },
            showSpecialModal:function(tid){//置为特殊订单
                $("#specialOrder").modal('show');
                $("#specialTid").val(tid);
            },
            editSpecial:function () {
                var _this = this;
                $.postRequest(thirdorderurl+"youzanorder/editSpecial",{
                    "str" : JSON.stringify({
                        "tid":$("#specialTid").val()
                    })
                },function (res) {
                    if(res.status=="200"){
                        _this.getOrderList(1);
                    }else {
                        common.lightBox.showMessage("标记有赞订单失败!");
                    }
                })
            }
        }
    })
});
